const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
const {billCanEdit, detectHasReceipt, updateInventory, hxYusf} = require("../bill/base");
const tools = require("../../tools/tool");

// 政策兑付作废
router.post('/pay/zcdfWaste', async ctx => {
    let user = ctx.user
    let body = ctx.request.body
    let tenantId = user.tenantId;
    let id = body.id
    let model = await db.models['sendDf'].findOne({
        where: {
            tenantId,
            id
        }
    })
    let transType = 153401
    // if(model.billState !== 'accounted') {
    //     return ctx.err('票据状态错误')
    // }
    if(model.dfType === '转预付') {
        transType = 153406
        let yfId = model.yfId
        let has = await db.models['invoiceDikou'].count({
            where: {
                tenantId,
                relId: yfId
            }
        })
        if(has > 0) {
            return ctx.err('预付票据已有抵扣产生，不能作废')
        }
    }
    await db.transaction(async ()=>{
        ctx.request.body.ids = [model.yfId]
        ctx.request.body.canWasteAuto = true
        ctx.request.body.transType = transType
        let ret = await toWasted(ctx)
        if(!ret.stat) {
            throw new Error(ret.msg)
        }
        let list = await db.query(`select * from send_df_detail where sendDfId=${model.id}`,{type: QueryTypes.SELECT})
        let logs = Object.assign(model, {infos: list})
        let logModel = db.models['sendDfLog'].build()
        logModel.tenantId = tenantId
        logModel.type = '删除'
        logModel.content = JSON.stringify(logs)
        logModel.cby = user.id
        logModel.createdAt = tools.getTime()
        await logModel.save()
        await db.models['sendDf'].destroy({
            where: {
                tenantId,
                id: model.id
            }
        })
        await db.models['sendDfDetail'].destroy({
            where: {
                tenantId,
                sendDfId: model.id
            }
        })
    })
    return ctx.suc('已作废')

})

const toWasted = async (ctx) => {
    let canWasteAuto = false // 是否可作废自动生成票据
    if(ctx.request.body.canWasteAuto) {
        canWasteAuto = true
    }
    try {
        let id = ctx.request.body.ids[0];
        let uid = ctx.user.id
        let tenantId = ctx.user.tenantId
        let invoice = await db.models['invoice'].findOne({
            where: {
                tenantId,
                id
            }
        })
        if(!invoice)  return ctx.err('未找到票据')
        if(!canWasteAuto) {
            if(invoice.isAuto === 1) {
                return ctx.err('不能退审自动生成的票据')
            }
        }
        let transType = tool.xe.toNumber(invoice.transType)
        if (!invoice) return ctx.err('没有找到票据')
        if (invoice.billState === 'del') return ctx.err('票据已被删除')
        if (invoice.billState !== 'accounted') return ctx.err('未审核票据')
        if (tool.xe.toNumber(invoice.isInit) === 1) return ctx.err('不能退审期初数据')
        if (transType === 153406 || transType === 153407) {
            let sqls = ` select top 1 b.billNo from invoice_dikou a inner join invoice b on a.iid=b.id and a.relId=${id} `;
            let used = await db.query(sqls, { type: QueryTypes.SELECT, plain: true })
            if (used) {
                return ctx.err(`已在票据 ${used.billNo} 中抵扣, 不能退审`)
            }
        }
        invoice.billState = 'del'
        invoice.wastedAt = tool.getTime()
        invoice.wastedBy = ctx.user.id
        invoice.updatedAt = tool.getTime()
        // 退审票据主表
        invoice.accountedAt = null;
        invoice.accountedBy = null
        await db.transaction(async () => {
            await invoice.save()
            await db.models['card'].update({
                billState: 'del'
            }, {
                where: {
                    tenantId: tenantId,
                    byIid: invoice.id
                }
            })
        })
        await tool.saveLogInvoice(tenantId, uid, invoice.id, "退审", invoice,);
        return ctx.suc('已退审')
    }
    catch (e) {
        return ctx.err(e)
    }
}

module.exports = router;
